package com.jzlin.funhub.admin.service.article;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzlin.funhub.admin.mapper.ArticleStarMapper;
import com.jzlin.funhub.admin.model.dto.ArticlePageDTO;
import com.jzlin.funhub.admin.model.entity.ArticleStar;
import com.jzlin.funhub.admin.model.req.ArticleStarReq;
import com.jzlin.funhub.admin.model.req.UserArticleStarPageReq;
import com.jzlin.funhub.framework.common.consts.BaseConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 文章收藏表 服务实现类
 * </p>
 *
 * @author jzlin
 * @since 2025-07-25
 */
@Service
public class ArticleStarService extends ServiceImpl<ArticleStarMapper, ArticleStar> {

    @Autowired
    private ArticleService articleService;

    /**
     * 当前登录用户是否收藏文章
     *
     * @param articleId 文章id
     * @return
     */
    public boolean ifCurrentUserHasStar(Long articleId) {
        if (!StpUtil.isLogin()) {
            return false;
        }
        Long userId = StpUtil.getLoginIdAsLong();
        return this.query()
                .eq("del", BaseConst.FLAG_FALSE)
                .eq("article_id", articleId)
                .eq("user_id", userId).exists();
    }

    /**
     * 点赞/取消点赞文章
     * @param req
     */
    @Transactional
    public void starArticle(ArticleStarReq req) {
        Long userId = StpUtil.getLoginIdAsLong();
        if (req.getFlag()) {
            int row = this.baseMapper.starArticle(userId, req.getArticleId());
            if (row > 0) {
                articleService.updateArticleStarCount(req.getArticleId(), true);
            }
        } else {
            boolean success = this.update()
                    .eq("article_id", req.getArticleId())
                    .eq("user_id", userId).set("del", BaseConst.FLAG_TRUE).update();
            if (success) articleService.updateArticleStarCount(req.getArticleId(), false);
        }
    }

    /**
     * 分页查询用户收藏的文章
     *
     * @return
     */
    public IPage<ArticlePageDTO> queryUserArticleStarPage(UserArticleStarPageReq req) {
        IPage<?> page = new Page<>(req.getCurrent(), req.getSize());

        return this.baseMapper.queryPageByUserId(page, req.getUserId());
    }
}
